package com.epam.qanda.listener;

import java.util.List;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.epam.qanda.db.model.Category;
import com.epam.qanda.db.model.ModeratorCategory;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.CategoryService;
import com.epam.qanda.db.service.ModeratorCategoryService;

public class CategoryListener implements ServletRequestListener {

	public void requestInitialized(ServletRequestEvent event) {

		HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
		HttpSession session = request.getSession();
		List<Category> categories = new CategoryService().getAllCategories();
		if (categories != null) {
			if (session.getAttribute("categories") != null) {
				session.removeAttribute("categories");
			}
			User user = (User) session.getAttribute("user");
			if (user != null && user.getRoleId() == 2) {
				List<ModeratorCategory> moderatorCategories = new ModeratorCategoryService()
						.getModeratorCategory(user.getId());
				session.setAttribute("moderatorCategories", moderatorCategories);
			}
			session.setAttribute("categories", categories);
		}

	}

	@Override
	public void requestDestroyed(ServletRequestEvent arg0) {
	}

}
